import type { Context } from 'koa'

interface ErrorResponse {
  code: string | number
  msg: string
  error?: any
  status?: number
}

const errHandler = (err: ErrorResponse, ctx: Context) => {
  let status = 500
  switch (err.code) {
    case '10001':
      status = 400 // 参数错误
      break
    case '10002':
      status = 409 // 冲突错误
      break
    case '10003':
      status = 401 // 未授权
      break
    case '10004':
      status = 403 // 禁止访问
      break
    case '10005':
      status = 404 // 资源不存在
      break
    default:
      status = 500 // 服务器错误
  }
  ctx.status = status
  ctx.body = {
    code: err.code,
    msg: err.msg || '服务器内部错误',
    data: err.error,
  }
}

export default errHandler
